﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using RBS.Core.BLL;
using RBS.Core.Model;
using RBS.Web.API.Models;
using V_OrderDetails = RBS.Core.Model.V_OrderDetails;

namespace RBS.Web.API.Areas.User.Controllers
{
    /// <summary>
    /// 
    /// </summary>
    public class ApiOrderController : ApiController
    {
        private ApiContext db = new ApiContext();

        /*public JsonData GetInviteFriend()
        {
            var jsonData = new JsonData { Success = false,Error = "123456"};
            return jsonData;
        }
         */
        /// <summary>
        /// 邀请好友聚餐
        /// </summary>
        /// <param name="ids">用户ID（1,2,3,4,5）</param>
        /// <param name="orderid">订单ID</param>
        /// <returns></returns>
        public JsonData GetInviteFriend(string ids, string orderid)
        { 
            var jsonData = new JsonData {Success = false};
            var msg = "";
            try
            {
                foreach (var id in ids.TrimEnd(',').Split(',').ToList())
                {
                   int isG=new RBS.Core.BLL.V_Guest().GetRecordCount(Convert.ToInt32(orderid), Convert.ToInt32(id)); 
                    if (isG > 0)
                    {
                        jsonData.Error += id + "已被邀请，";
                        continue;
                    }

                    var model = new RBS.Core.Model.D_Guest
                        {
                            GuestId = Convert.ToInt32(id),
                            OrderId = Convert.ToInt32(orderid),
                            Status = 0
                        };
                    new RBS.Core.BLL.D_Guest().Add(model);
                }
                var orderModel = new RBS.Core.BLL.D_Order().GetModel(Convert.ToInt32(orderid));
                var guestList = new RBS.Core.BLL.V_Guest().GetModelList(Convert.ToInt32(orderid));
                jsonData.Data =null;
                try
                {
                    RBS.Core.BLL.SmsMessage smsMessage = new SmsMessage();
                    var ymb = guestList.Aggregate("", (current, guest) => current + (guest.Mobile + ","));
                    string content = "您的朋友在[" + orderModel.HotelName + "]预定的饭局,邀请您参加！";
                    smsMessage.Send(ymb.TrimEnd(','), content, 1, out msg);
                    jsonData.Success = true;
                }
                catch  (Exception exception)
                {
                    jsonData.Data = null;
                    jsonData.Success = false;
                    jsonData.Error = exception.Message;
                }  
            }
            catch (Exception ex)
            {
                jsonData.Success = false;
                jsonData.Error = ex.Message;
            }
            return jsonData;
        } 
         

        // POST api/apiorder
        /// <summary>
        /// 新增订单
        /// </summary>
        /// <param name="value"></param>
        public JsonData Post([FromBody]OrderModel value)
        {
            var jsonData = new JsonData { Success = false };
            
                try
                {
                    //RBS.Core.Logs.LogManager.WriteLog("order1", ConvertJson.EntityToJson(value)); 
                    //修改订单
                    var orderUpdate = db.Order.Find(value.Order.Id);
                    orderUpdate.OrderTime = value.Order.OrderTime;
                    orderUpdate.DineTable = value.Order.DineTable;
                    db.Entry(orderUpdate).State = EntityState.Modified;
                    db.SaveChanges(); 
                 
                    foreach (var items in value.Detail)
                    {
                        //如果下单则新增一条
                        VOrderDetails items1 = items;
                        var item = db.OrderDetails.Where(c => c.HCId == items1.HCId && c.OrderId == items1.OrderId);
                        var count = item.Count() - items1.Num; 
                     
                            if (count > 0)
                            {
                               // RBS.Core.Logs.LogManager.WriteLog("删除", ConvertJson.EntityToJson(items1)); 
                                var deleteItem =
                                    db.OrderDetails.Where(
                                        c => c.HCId == items1.HCId && c.OrderId == items1.OrderId && c.State == 1);
                                for (int i = 0; i < count; i++)
                                {
                                    db.OrderDetails.Remove(deleteItem.First());
                                    db.SaveChanges();
                                }
                            }
                            else if (count < 0)
                            {
                                 
                                //添加 
                                var cook = db.HotelCookbook.Find(items.HCId);
                                 var cookCount = Convert.ToInt32(cook.EstimateClear);

                                 if (count > cookCount && cookCount > 0)
                                 {
                                     jsonData.Success = false;
                                     jsonData.Error += cook.Name + "库存数量不足,";
                                     continue; 
                                 } 
                    
                                for (int i = count; i < 0; i++)
                                {
                                    if (cookCount == 0)
                                        continue;

                                    cookCount--; 

                                    var orderTemp = new RBS.Core.Model.D_Order_Details
                                        {
                                            OrderId = value.Order.Id,
                                            UId = value.Order.U_Id,
                                            HCId = items.HCId,
                                            Num = 1,
                                            // IsGuest = items.IsGuest,
                                            State = 1,
                                            DisAmount = cook.Discount,
                                            CName = cook.Name,
                                            Price = cook.Price,
                                            Weight=0,
                                            OperateDate = DateTime.Now
                                        };
                                    if (value.Order.OrderState == (int)RBS.Common.RBSEnums.OrderStatus.Dining)
                                    {
                                        orderTemp.State = 10;
                                    }
                                    if (cook.StartIdentification == 0)
                                    {
                                        orderTemp.State = 3;
                                    }
                                    orderTemp= db.OrderDetails.Add(orderTemp);
                                    db.SaveChanges();       
                                    //如果是就餐后加菜则添加至催菜表 
                                    if (value.Order.OrderState == (int) RBS.Common.RBSEnums.OrderStatus.Dining)
                                    {
                                        var cuicai = new RBS.Core.Model.D_CuiCai
                                        {
                                            DishId = orderTemp.Id,
                                            DishName = orderTemp.CName,
                                            DishState = orderTemp.State,
                                            OrderId = orderTemp.OrderId,
                                            DineTable = value.Order.DineTable,
                                            CookChef = "",
                                            CookWeight = 100,
                                            TimeWeight = 0,
                                            PressWeight = 0,
                                            OtherWeight = 0,
                                            OrderConfirmTime = DateTime.Now
                                        }; 
                                        RBS.Core.Logs.LogManager.WriteLog("添加催菜表", ConvertJson.EntityToJson(cuicai));
                                        db.CuiCai.Add(cuicai);
                                        db.SaveChanges();
                                        jsonData.Success = true;
                                    }
                                    
                                }
                            } 
                    } 
                    
                }
                catch (Exception ex)
                {
                     RBS.Core.Logs.LogManager.WriteLog("error", ex.Message);
                    jsonData.Error = ex.Message;
                } 
            return jsonData;
        }
          
    }
}
